package cn.yedong.org.service.impl;
/**
 * 业务实现类：部门
 */


import cn.yedong.basic.service.impl.BaseServiceImpl;
import cn.yedong.org.domain.Department;
import cn.yedong.org.mapper.DepartmentMapper;
import cn.yedong.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务接口：部门
 */

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    /**
     * 获取部门树
     * @return
     */
    @Override
    public List<Department> deptTree() {
        //1.将所有部门信息保存在map集合中，方便根据id获取部门信息，就不用查询数据库了【相当于查询所有数据将其放到内存中】
        //1.1创建一个map集合，用于保存所有部门信息【部门id，部门】
        Map<Long, Department> map = new HashMap<>();
        //1.2查询所有部门
        List<Department> departments = departmentMapper.loadAll();
        //1.3遍历部门集合装进map
        for (Department department : departments) {
           map.put(department.getId(),department);
        }
        //2.遍历所有部门，如果是顶级部门【parent_id == null】,就将其加到部门树
        //2.1创建List集合，用于装 无限极部门树
        List<Department> deptTree = new ArrayList<>();
        //2.2遍历部门集合
        for (Department department : departments) {
            //如果这个部门没有父id，就将直接它装到部门树
            if(department.getParent_id() == null){
                deptTree.add(department);
            }else{
                //3.如果不是顶级部门，找到自己的父部门，将自己加到父部门的children
                //3.1获取父部门id
                Long parentId = department.getParent_id();
                //3.2根据父部门id查询父部门
                Department parentDepartment = map.get(parentId);
                //防止父部门为空时报空指针异常
                if(parentDepartment != null){
                    //3.3将自己装到父部门children
                    parentDepartment.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }
}
